<!--中转管理-收货列表-->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e"
      :cell-class-name="cellClassMethod">
    </ex_super_table_page>
    <!-- <detail_transfer ref="DetailDescTable" /> -->

    <taskAssign ref="taskAssign" :title="$tt('label_receiving_task_assign')" @afterSubmit="afterSubmitTask"
      :intoTableOption="[
      { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 120, 'show-overflow-tooltip': true, },
      {
        type: 'operate', operate: [{
          label: 'title_task_assgin_record', click: (row) => this.$refs.detail_task_record.show({
            title: `${this.$tt('label_inbound_code')}:${row.code}/${this.$tt('label_order_code')}:${row.receivingOrderCode}`,
            urlConfig: {
              url: '/wms-api/inbound/WmsInboundTransitReceivingRpc/selectDetail.json',
              data: { id: row.id }
            },
            urlDataHandle: (res) => res.data.receivingTaskUserId ? [res.data] : []
          })
        }]
      }
    ]" />

    <detail_task_record ref="detail_task_record" :tableModel="[
      { key: 'code', label: 'label_inbound_code', 'min-width': 120, 'show-overflow-tooltip': true, },
      {
        key: 'receivingTaskUserName', label: 'label_receiving_task_user', 'min-width': 120, 'show-overflow-tooltip': true,
        formatter: (r, c, v, i) => this.$formatNameCode(v, r.receivingTaskUserCode)
      }]" />
    <transfer_quick_receive ref="transfer_quick_receive" @submitSuccess="submitQuickTackDeliveryAfter" />
    <transfer_receive_measure ref="transfer_receive_measure" @submitSuccess="reload()" />


    <report_anomaly ref="report_anomaly" :orderTypeList="['INBOUND']" system="WMS" @afterSubmitSuccess="reload()" />

    <common_print_dialog ref="print_inbound_inventory"
      :title="$tt('label_print_any', { type: 'label_inbound_inventory', i18n: true })" :tableModel="[
      { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'expectBoxQty', label: 'label_expected_box_number', 'width': 80, },
      { key: 'expectSkuQty', label: 'label_expected_sku_number', 'width': 80, },
    ]" printUrl="/wms-api/inbound/WmsInboundTransitReceivingRpc/printInboundList.json" :printHandler='(data, list) => {
      return {
        printList: list.map(it => {
          return {
            id: it.id,
            clientName: data.clientName,
            printerName: data.printerName,
            printCount: data.printNumSum,
          }
        })
      }
    }' previewUrl="/wms-api/inbound/WmsInboundTransitReceivingRpc/previewInboundList.json" :previewHandler='(data, row) => {
      data.id = row.id
      return data
    }' />

    <common_print_dialog ref="print_bebox_inventory"
      :title="$tt('label_print_any', { type: 'label_bebox_inventory', i18n: true })" :tableModel="[
      { key: 'code', label: 'label_inbound_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 140, 'show-overflow-tooltip': true, },
      { key: 'expectBoxQty', label: 'label_expected_box_number', 'width': 80, },
      { key: 'expectSkuQty', label: 'label_expected_sku_number', 'width': 80, },
    ]" printUrl="/wms-api/inbound/WmsInboundTransitReceivingRpc/printBoxList.json" :printHandler='(data, list) => {
      return {
        printList: list.map(it => {
          return {
            id: it.id,
            clientName: data.clientName,
            printerName: data.printerName,
            printCount: data.printNumSum,
          }
        })
      }
    }' previewUrl="/wms-api/inbound/WmsInboundTransitReceivingRpc/previewBoxList.json" :previewHandler='(data, row) => {
      data.id = row.id
      return data
    }' />

    <print_pre_box_generate ref="print_pre_box_generate" />
    <print_sku ref="print_sku" itemKey="skuId" />
    <print_box ref="print_box" />

  </div>
</template>
<script>
import print_sku from '@/component/print/print_sku'
import print_box from '@/component/print/print_box'
import print_pre_box_generate from '../component/print/print_pre_box_generate.vue';

import business_function from "@/common/business_function"

import superTablePageFunction from '@/mixin/super-table-page-function';
import taskAssign from '@/component/wms/taskAssign.vue';
import transfer_quick_receive from './dialog/transfer_quick_receive.vue';
import transfer_receive_measure from './dialog/transfer_receive_measure.vue';

import detail_task_record from '@/component/dialog/detail_task_record.vue';
import report_anomaly from '@/component/dialog/report_anomaly.vue'
import common_print_dialog from '@/component/print/common_print_dialog.vue';


import page_table_model_manage from '@/mixin/page_table_model_manage';

import emitOnFunction from '@/mixin/emit-on-function';
const emitKey = 'transfer=>receiving_list'
export default {
  title: "title_transfer_receiving_list",
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: {
    taskAssign, detail_task_record, print_sku, print_box, print_pre_box_generate,
    transfer_quick_receive, transfer_receive_measure,
    report_anomaly, common_print_dialog,
  },
  data() {
    return {
      selection: [],
      dialogDetailCode: "",
      dialogDetail: false,

      // dialogQuickReceiving: false,
      selectList: [],

      option: {
        search: {
          model: [
            { label: "label_inbound_code", key: "code", },
            { label: "label_order_code", key: "receivingOrderCode", },
            {
              label: "label_customer", key: "customerId", type: "common_customer_choose"
            },
            {
              label: "label_inbound_status", key: "status", type: 'select', enum: 'OverseasStatusEnum'
            },
            { label: "label_delivery_type", key: "deliveryType", type: 'select', enum: 'DeliveryTypeEnum' },
            { label: "label_is_first_arrival", key: "isFirstArrival", type: 'select', enum: 'YesOrNoEnum' },
            { label: 'label_business_type', key: 'bizType', type: 'select', enum: 'BizTypeEnum', fold: true, },
            { label: "label_track_code", key: "trackingNumber", fold: true, },
            { label: "label_expected_arrival_date", key: "expectedDate", type: 'date-picker', fold: true, },
          ],
        },
        actionExtra: [
          {
            label: 'label_batch_print', type: "more",
            list: [
              {
                label: 'label_print_sku_barcode',
                click: () => {
                  this.printSkuTag(this.selection)
                },
              },
              {
                label: 'label_print_box_tag',
                click: () => {
                  this.printBoxTag(this.selection)
                },
              },
              {
                label: { _key: 'label_print_any', type: 'label_inbound_inventory', i18n: true },
                click: () => {
                  if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
                  this.$refs.print_inbound_inventory.show(this.selection)
                }
              },
              {
                label: { _key: 'label_print_any', type: 'label_bebox_inventory', i18n: true },
                click: () => {
                  if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
                  this.$refs.print_bebox_inventory.show(this.selection)
                }
              },
            ]
          },
          {
            label: 'label_income_good_measure', auth: 'wms_transfer_income_good_measure', click: (row) => {
              if (_.isEmpty(this.selection)) {
                return this.$message.error(this.$tt("tip_please_select_order"))
              } else if (this.selection.some(it => it.receivingStatus == 'NOT_RECEIVING')) {
                const tip = this.selection.filter(it => it.receivingStatus == 'NOT_RECEIVING').map(it => it.code).join(',')
                this.$alert(tip, this.$tt("label_below_order_no_receive"), {
                  type: 'warning'
                });
                return
              } else if (this.selection.some(it => it.checkoutStatus != 'NOT_CHECKOUT')) {
                const tip = this.selection.filter(it => it.checkoutStatus != 'NOT_CHECKOUT').map(it => it.code).join(',')
                this.$alert(tip, this.$tt("label_below_order_has_checkout"), {
                  type: 'warning'
                });
                return
              }
              this.$refs.transfer_receive_measure.show({ tableList: this.selection })
            }
          },
          {
            label: 'label_task_assign', auth: 'wms_transfer_receive_task_assign', attrs: { type: 'primary' },
            click: this.clickTaskAssignment,
          },

          // {
          //   label: 'label_packing_box_inventory',
          //   click: this.$noFunction,
          // },
          {
            label: 'label_quick_receiving', auth: 'wms_transfer_quick_receive', attrs: { type: 'primary' },
            click: this.clickQuickTackDelivery,
          },
          // {
          //   label: 'label_export',
          //   click: this.$noFunction,
          // },
          { label: 'label_download_attachment_zip', click: this.downloadAttachmentZip },



        ],
        table: {
          url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/selectPage.json",
          model: this.init_table_model(),
        }
      },
    };
  },
  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, },
        {
          type: 'expandDesc', 'width': 100,
          expandDesc: {
            class: "desc_flex_row",
            column: 4, border: true, direction: 'vertical', labelClassName: 'widthdiv4', contentClassName: 'widthdiv4',
            model: [],
          },
        },

        { key: 'trackingNumber', label: 'label_track_code', keyShow: 'expandDesc', 'min-width': 100, 'show-overflow-tooltip': true, },
        { key: 'referenceNo', label: 'label_customer_reference_no', keyShow: 'expandDesc', 'min-width': 100, 'show-overflow-tooltip': true, },

        { key: 'supplyName', label: 'label_logistics_supplier', 'width': 120, 'show-overflow-tooltip': true, keyShow: 'expandDesc', },


        {
          key: 'productName', label: 'label_logistics', 'width': 120, 'show-overflow-tooltip': true,
          keyShow: 'expandDesc', formatter: (r, c, v) => this.$formatNameCode(v, r.productCode)
        },

        { key: 'logisticsStatus', label: 'label_logistics_status', keyShow: 'expandDesc', 'min-width': 100, 'show-overflow-tooltip': true, },
        { key: 'transitWarehouseCode', label: 'label_transit_warehouse', keyShow: 'expandDesc', 'min-width': 100, 'show-overflow-tooltip': true, },

        { key: 'code', label: 'label_inbound_code', },
        { key: 'receivingOrderCode', label: 'label_order_code', 'min-width': 120, 'show-overflow-tooltip': true, },
        {
          key: 'customerName', label: 'label_customer_info', 'min-width': 100, 'show-overflow-tooltip': true,
          formatter: (r, c, v) => this.$formatNameCode(v, r.customerCode),
        },
        { key: 'expectBoxQty', label: 'label_expected_box_number', 'width': 100, },
        { key: 'expectSkuQty', label: 'label_expected_sku_number', 'width': 100, },
        { key: 'destinationWarehouseCode', label: 'label_destination_warehouse', 'width': 120, 'show-overflow-tooltip': true, },

        {
          key: 'status', label: 'label_status', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "OverseasStatusEnum")
        },
        {
          label: 'label_business_type', key: 'bizType', 'width': 120, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "BizTypeEnum")
        },
        { key: 'inboundType', label: 'label_inbound_type', 'width': 120, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$enumShow(v, "InboundTypeEnum") },
        {
          key: 'isAutomaticWarehouseArea', label: 'label_is_auto_location', 'width': 110, 'show-overflow-tooltip': true,
          render: (h, { row, column }) => this.$renderText(h, row[column.property], { enum: "YesOrNoEnum" })
        },
        {
          key: 'boxDetailIsEmpty', label: 'label_require_sku_detail_manage', 'width': 120,
          render: (h, { row, column }) => {
            const v = row[column.property]
            return (<div class={v == 'Y' ? 'color_danger' : 'color_success'}>{this.$enumShow(v, "YesOrNoOppositeEnum")}</div>)
          }

        },
        {
          key: 'boxIsEmpty', label: 'label_is_box_code_manage', 'width': 120,
          render: (h, { row, column }) => {
            const v = row[column.property]
            return (<div class={v == 'Y' ? 'color_danger' : 'color_success'}>{this.$enumShow(v, "YesOrNoOppositeEnum")}</div>)
          }
        },
        {
          type: 'operate', width: 160, fixed: 'right', operate: [
            {
              type: 'more',
              items: [
                { label: 'label_view_detail', click: (row) => { this.clickDetail(row) } },
                {
                  label: 'label_print_sku_barcode',
                  click: (row) => {
                    this.printSkuTag([row])
                  },
                },
                {
                  label: 'label_print_box_tag',
                  click: (row) => {
                    this.printBoxTag([row])
                  },
                },
                {
                  label: { _key: 'label_print_any', type: 'label_inbound_inventory', i18n: true }, click: (row) => {
                    this.$refs.print_inbound_inventory.show([row], { single: true })
                  }
                },
                {
                  label: { _key: 'label_print_any', type: 'label_bebox_inventory', i18n: true }, click: (row) => {
                    this.$refs.print_bebox_inventory.show([row], { single: true })
                  }
                },

                {
                  label: 'label_income_good_measure', auth: 'wms_transfer_income_good_measure',
                  disabled: (row) => row.receivingStatus == 'NOT_RECEIVING' || row.checkoutStatus != 'NOT_CHECKOUT',
                  click: (row) => {
                    this.$refs.transfer_receive_measure.show({ tableList: [row] })
                  }
                },
                // { label: 'label_print_inbound_code' },
                // { label: 'label_download_attachment' },
                {
                  label: 'label_reset_receiving', auth: 'wms_transfer_reset_receive',
                  disabled: (row) => row.receivingStatus != 'RECEIVING_COMPLETED' || row.checkoutStatus != 'NOT_CHECKOUT',
                  click: (row) => { this.clickResetReceiving(row) }
                },
                {
                  label: 'label_receiving', auth: '/page/wms/transfer/receiving',
                  disabled: (row) => row.receivingStatus != 'NOT_RECEIVING',
                  click: (row) => { this.gotoReceiving(row) }
                },
                {
                  label: 'label_acceptance', auth: '/page/wms/transfer/check',
                  disabled: (row) => row.acceptanceStatus == 'ACCEPTANCE_COMPLETED',
                  click: (row) => { this.gotoCheck(row) }
                },
                { label: 'label_report_exception', click: (row) => this.reportAnomaly(row), },
              ]
            }
          ]
        }
      ]
    },
    printSkuTag(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_order'))
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/selectBatchDetail.json",
        method: 'post', loading: true,
        data: { ids: rows.map(it => it.id) },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            this.$confirm(this.$tt('tip_is_confirm_print_inbound_order_sku_count'), this.$tt('label_tip'), {
              type: 'warning'
            }).then(() => {
              const list = _.flatMap(res.data.rows, it => !_.isEmpty(it.inboundOrderSkuList) ? it.inboundOrderSkuList : it.detailList)
              const uq = _.uniqBy(list, it => it.skuId).map(it => {
                it.printNum = _.reduce(list.filter(item => item.skuId == it.skuId), (r, v) => this.$math_add(r, Number(v.quantity)), 0)
                return it
              })

              this.$refs.print_sku.show(uq)
            }).catch((action) => {

              if (action === 'cancel') {
                const list = _.flatMap(res.data.rows, it => it.detailList)
                const uq = _.uniqBy(list, it => it.skuId)
                this.$refs.print_sku.show(uq)
              }
            });

          }

        }
      })
    },
    printBoxTag(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt('tip_please_select_order'))
      const list = _.uniqBy(rows, it => (it.boxIsEmpty == 'Y' && it.packingBoxStatus != "PACKING_BOX_COMPLETED") || it.boxDetailIsEmpty == 'Y')
      if (list.length >= 2) {
        return this.$message.error(this.$tt('tip_has_box_code_no_with_no_box_code_inbound_order_print'))
      }
      if (list.some(it => (it.boxIsEmpty == 'Y' && it.packingBoxStatus != "PACKING_BOX_COMPLETED") || it.boxDetailIsEmpty == 'Y')) {
        if (_.uniqBy(rows, it => it.customerId).length >= 2) {
          return this.$message.error(this.$tt('tip_customer_different'))
        }
        this.$refs.print_pre_box_generate.show({ list: rows, code: _.head(rows).code })

      } else {
        this.$ajax({
          url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/selectBatchDetail.json",
          method: 'post', loading: true,
          data: { ids: rows.map(it => it.id) },
          success: (res) => {
            if (res && res.data && res.data.rows) {
              const reslist = _.flatMap(res.data.rows, it => it.detailList)


              const boxNo_group = _.groupBy(reslist, it => it.boxId)
              const printData = []
              _.forOwn(boxNo_group, (value, k) => {
                const order = _.find(res.data.rows, it => it.code == _.head(value).receivingCode)
                printData.push(
                  {
                    orderId: order ? order.id : "",
                    boxId: k,
                    binNo: _.head(value).boxNo,
                    targetWarehouse: order ? order.destinationWarehouseName : "",
                    customerCode: order ? order.customerCode : "",
                    skuCategoryNum: _.uniqBy(value, sku => sku.skuId).length,
                    skuCount: _.reduce(value, (r, v) => this.$math_add(r, Number(v.quantity)), 0),
                  }
                )
              })
              this.$refs.print_box.show(printData)


            }

          }
        })

      }
    },
    reportAnomaly(row) {
      this['$refs']['report_anomaly'].showNew({
        formDisabled: true,
        onlySetData: true,
        data: {
          customerName: row.customerName,
          customerCode: row.customerCode,
          customerId: row.customerId,
          orderNo: row.code,
          orderType: 'INBOUND',
        },

      })
    },
    cellClassMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'status') {
        if (row.status == 'TRANSIT_WAIT_RECEIVING') {
          return 'color_primary'
        } else if (row.status == 'TRANSIT_WAIT_PICKING') {
          return 'color_primary'
        } else if (row.status == 'TRANSIT_PARTIAL_OUTBOUND') {
          return 'color_warning'
        } else if (row.status == 'TRANSIT_OUTBOUND') {
          return 'color_success'
        }
      }
      return ""
    },


    gotoReceiving(row) {
      this.$router.push({ name: '/page/wms/transfer/receiving', params: { 'code': row.code } })
    },
    gotoCheck(row) {
      this.$router.push({ name: '/page/wms/transfer/check', params: { 'receivingCode': row.code } })
    },
    clickDetail(row) {

      // this.$refs['DetailDescTable'].show({ params: { id: row.id }, title: `${this.$tt('label_inbound_code')}:${row.code}` })
      this.$router.push({ name: '/page/wms/transfer/inbound_detail', query: { 'id': row.id } })
    },
    clickResetReceiving(row) {
      this.$confirm(this.$tt('text_is_sure_reset_receiving'), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/resetReceiving.json",
          method: 'post', type: 'json',
          data: { receivingId: row.id },
          success: (res) => {
            this.$message.success(this.$tt('tip_submit_success'))
            this.reload()
          }
        })
      }).catch(() => {

      });
    },
    //任务分配
    clickTaskAssignment(e) {
      let _list = this.getSelection();
      if (_list.length <= 0) return this.$message.error(this.$tt("tip_noSelect_receiving_list"))
      if (_list.some(it => !['TRANSIT_WAIT_INBOUND', 'TRANSIT_WAIT_RECEIVING'].includes(it.status))) {
        return this.$message.error(this.$tt('tip_transfer_order_StatusNoChangeTask'))
      }
      this.$refs['taskAssign'].show(this.$loginUser.currentWarehouseId, _list)
    },
    afterSubmitTask({ select, list }) {

      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/assigningReceivingTask.json",
        method: 'post', type: 'json',
        data: {
          ids: list.map(it => it.id),
          receivingUserId: select.userId,
          receivingUserCode: select.userCode,
          receivingUserName: select.userName,
        },
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.reload()
          this.$refs['taskAssign'].hide()
        }
      })
    },
    //快速一键收货
    clickQuickTackDelivery() {

      let _list = this.getSelection();
      if (_list.length <= 0) {
        return this.$message.error(this.$tt("tip_noSelect_receiving_list"))
      }
      if (_list.some(it => !['TRANSIT_WAIT_INBOUND', 'TRANSIT_WAIT_RECEIVING', 'TRANSIT_WAIT_PUTAWAY'].includes(it.status))) {
        return this.$message.error(this.$tt('tip_status_error_no_operate'))
      }
      this.$refs.transfer_quick_receive.show({
        tableList: _.cloneDeep(_list)
      })

    },

    submitQuickTackDeliveryAfter() {
      this.reload()
      this.$emitPage("transfer=>checkout_list", 'reload')

    },
    downloadAttachmentZip() {
      business_function.confirmOperateBaseSelectOrForm.call(this, {
        data: this.$refs.SuperTablePage.getSearchData(),
        model: this.option.search.model,
        selection: this.selection,
        callback: (selection, data) => {
          let params = {}
          if (!_.isEmpty(selection)) {
            params = {
              codes: selection.map(it => it.code)
            }
          } else {
            params = data
          }
          this.$downloadFile({
            window: true,
            url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/batchDownloadAttached.json",
            data: params,
          })
        }
      })

    },
  }
};

</script>
<style></style>
